﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MX.Core.Http.WebAction
{
    /// <summary>
    /// xwwwformurlencoded类型表单信息类
    /// 这种是最常用的表单类型
    /// </summary>
    public class XWwwFormUrlencodedPostInfo : PostInfo
    {
        public bool EncodeValue { get; set; }
        public XWwwFormUrlencodedPostInfo(NameValueCollection formData, string formEncoding)
            : base(PostContentType.Application_XWwwFormUrlencoded(formEncoding.ToUpper()), formEncoding)
        {
            EncodeValue = true;
            FormData = formData;
        }


        public XWwwFormUrlencodedPostInfo(NameValueCollection form)
            : this(form, "utf-8")
        {
        }

        public XWwwFormUrlencodedPostInfo(string postString, bool isEncoding = false)
            : this(GetQueryParameter(postString, "utf-8", isEncoding), "utf-8")
        {

        }

        static protected NameValueCollection GetQueryParameter(string url, string formEncoding, bool isEncoding)
        {

            NameValueCollection pars = new NameValueCollection();
            var paraString = url.Substring(url.IndexOf("?") + 1, url.Length - url.IndexOf("?") - 1).Split('&');
            for (int i = 0; i < paraString.Length; i++)
            {
                var index = paraString[i].IndexOf('=');
                 
                var name = paraString[i].Substring(0, index);
                var value = paraString[i].Substring(index+1, paraString[i].Length-index-1);
                value = isEncoding ? UrlUnit.UrlEncode(value, Encoding.GetEncoding(formEncoding)) : value;
                pars.Add(name, value);
            }
            return pars;
        }

        protected string UrlEconded(NameValueCollection postData)
        {
            if (postData == null) {
                return "";
            }
            StringBuilder strPost = new StringBuilder();
            foreach (var key in postData.AllKeys)
            {
                strPost.Append(key);
                strPost.Append("=");
                strPost.Append(EncodeValue ? UrlUnit.UrlEncode(postData[key], Encoding.GetEncoding(FormEncoding)) : postData[key]);
                strPost.Append("&");
            }
            strPost = strPost.Remove(strPost.Length - 1, 1);
            return strPost.ToString();
        }
        public NameValueCollection FormData { get; set; }
        public override string GetPostString()
        {
            return UrlEconded(FormData);
        }

        public override byte[] GetPostData()
        {
            Encoding code = Encoding.GetEncoding(FormEncoding);
            return code.GetBytes(GetPostString());
        }
    }
}
